<template>
  <el-dialog
    class="flow-dialog"
    title="分配角色"
    :model-value="visible"
    width="40%"
    destroy-on-close
    center
    modal
    :close-on-click-modal="false"
    :show-close="false"
  >
    <div style="text-align: center">
      <el-transfer
        v-model="checked"
        :data="data"
        filterable
        :titles="['未分配', '已分配']"
        :button-texts="['移除', '分配']"
        @change="handleChange"
      />
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button
          type="danger"
          :loading="loading"
          :icon="useRenderIcon('material-symbols:close')"
          @click="close()"
        >
          关闭
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script>
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { defineComponent, ref } from "vue";
import { bindRole, roleBindInfo, unbindRole } from "@/api/role";

const loading = ref(false);
const visible = ref(false);
const data = ref([]);
const checked = ref([]);
const roleId = ref("");

const close = () => {
  visible.value = false;
};
const openLinker = row => {
  visible.value = true;
  roleId.value = row.id;
  initTransfer(roleId.value);
};
const initTransfer = roleId => {
  data.value = [];
  checked.value = [];
  roleBindInfo(roleId).then(res => {
    for (const index in res.all) {
      const role = res.all[index];
      data.value.push({
        key: role.id,
        label: `${role.name}(${role.code})`,
      });
    }
    for (const index in res.bound) {
      const role = res.bound[index];
      checked.value.push(role.id);
    }
  });
};
const handleChange = (current, move, keys) => {
  if ("right" === move) {
    bindRole(roleId.value, keys).then(res => {
      for (const index in res) {
        const role = res[index];
        checked.value.push(role.id);
      }
    });
  } else if ("left" === move) {
    unbindRole(roleId.value, keys).then(res => {
      for (const index in res) {
        const role = res[index];
        checked.value.push(role.id);
      }
    });
  }
};

export default defineComponent({
  setup() {
    return {
      loading,
      visible,
      data,
      checked,
      close,
      useRenderIcon,
      handleChange,
    };
  },
});

export function initLinker() {
  return {
    openLinker,
  };
}
</script>

<style scoped></style>
